$(function(){
	var Section = Yo.Section;
	var User = Yo.User;
	var Utils = Yo.Utils;
	var Req = Yo.Req;
	var Pager = Yo.Pager;

	Section.addInter(/(pageScanerList|pageMeetingList|pageStat|pageStatChart|pageChangePwd|chooseScanerMeetingModal)/, function(page){
		// 先登录啊
		var user = User.get();
		if(user)
			return true;

		Section.go('pageChangeUser', true);
		return false;
	});

	// 查询打卡记录列表
	var isAlreadyLoadStat = false;
	Section.addPageFn('pageStat', function(){
		if(!isAlreadyLoadStat){
			showStatList();
			isAlreadyLoadStat = true;
		}
	});

	// 切换用户，登出
	Section.addPageFn('pageChangeUser', function(){
			var user = User.get();
			if(user){
				User.remove();
				$.get('/ibid/logout');

				showCompanyUser();
			}
	});

	// 统计图
	Section.addPageFn('pageStatChart', function(){
		showStatChart();
	});

	// *** *** *** *** *** *** *** *** *** *** *** *** 
	// check if user already login, cookie can be setted if server session is ok when page loaded
	var user = User.getFromCookie();
	if(user){
		User.set(user);
	}else{
		User.remove();
	}
	showCompanyUser(user);

	// 是否默认就进入一个子页面
	var params = Utils.params();
	if(params.defaultPage){
		if('stat' == params.defaultPage){
			Section.go('pageStat');
		}else if('showScaner' == params.defaultPage){
			Section.go('pageScanerList');
		}else if('showMeeting' == params.defaultPage){
			Section.go('pageMeetingList');
		}
	}

	// 修改密码
	$('#btnChangePwd').click(function(e){
		e.preventDefault();

		var changePwd1 = $('#changePwd1').val();
		var changePwd2 = $('#changePwd2').val();

		if(!changePwd1 || !changePwd2 || changePwd1 != changePwd2){
			Utils.alert('两次输入的密码必须一致！');
			return false;
		}

		Req.post('/ibid/change-pwd', {pwd: changePwd2}, function(data){
			$('#changePwd1').val('');
			$('#changePwd2').val('');

			Section.hide('pageChangePwd');
		});
	});

	// 用户登录
	$('#btnChangeUser').click(function(e){
		e.preventDefault();

		var companyId = $('#inputCompanyId').val();
		var pwd = $('#inputPwd').val();

		if(!companyId || !pwd){
			Utils.alert('请输入公司ID和密码！');
			return false;
		}

		Req.post('/ibid/login', {companyId: companyId, pwd: pwd, isRaw: 'true'}, function(data){
			if(!data.flag){
				Utils.alert('公司ID不存在或密码不正确！');
				return false;
			}

			$('#inputCompanyId').val('');
			$('#inputPwd').val('');

			User.set(data);
			showCompanyUser(data);

			Section.hide('pageChangeUser');
		});	
	});

	// 选择日期范围进行查询
	$('#dateRangeList').on('click', 'a', function(e){
		e.preventDefault();

		var target = $(e.target);
		if(!target.is('a')){
			target = target.closest('a');
		}
		var date = target.attr('value');

		Section.hide('chooseDateModal');

		showStatList(date);

		return false;
	});

	// 选择打卡器/会议进行查询
	$('#scanerMeetingRangeCancel').click(function(){
		showStatList(null, '-');
		Section.hide('chooseScanerMeetingModal');
	});

	$('#scanerMeetingRangeList').on('click', 'a', function(e){
		e.preventDefault();

		var target = $(e.target);
		if(!target.is('a')){
			target = target.closest('a');
		}
		var id = target.attr('data-id');
		var name = target.attr('data-name');

		Section.hide('chooseScanerMeetingModal');

		var scaner = {id: id, name: name};
		showStatList(null, scaner);

		return false;
	});

	// 翻页显示记录
	$('#btnPagePre').click(function(e){
		e.preventDefault();

		showRecordInPager(null, pager.pageNum - 1);
	});

	$('#btnPageNext').click(function(e){
		e.preventDefault();

		showRecordInPager(null, pager.pageNum + 1);
	});

	// *** *** *** *** *** *** *** *** *** *** *** ***
	var lastQueryRecordList;
	var lastQueryBanner = '';
	var pager = new Pager(1, 10, 0);
	function showRecordInPager(ll, pageNum, banner){
		if(ll)
			lastQueryRecordList = ll;
		if(banner)
			lastQueryBanner = banner;

		pager.pageNum = pageNum || 1;
		pager.totalCount = lastQueryRecordList.length;
		var subList = lastQueryRecordList.slice(pager.getStart(), pager.getEnd());

		var tpl = '' + 
			'<li class="{3}">' + 
			' <div class="row">' + 
			'	<div class="col col-20">{0}</div>' + 
			'	<div class="col col-20">{1}</div>' + 
			'	<div class="col col-60">{2}</div>' + 
			' </div>' +
			'</li>';

		var str = '<li class="table-view-cell table-view-divider" id="statBanner">{0}</li>'.format(lastQueryBanner);
		_.each(subList, function(it, i){
			str += tpl.format(it.userName || '?', it.scanerName, moment(it.dd).format('YYYY-MM-DD hh:mm:ss'), i % 2 == 0 ? '' : 'even');
		});
		$('#statRecordList').html(str);

		if(pager.hasPre()){
			$('#btnPagePre').show();
		}else{
			$('#btnPagePre').hide();
		}

		if(pager.hasNext()){
			$('#btnPageNext').show();
		}else{
			$('#btnPageNext').hide();
		}

		$('#labelTotalCount').text('记录数:{0} - {1}/{2}'.format(lastQueryRecordList.length, pager.pageNum, pager.getTotalPageNum()));
	};

	// 柱状图
	var chart;
	var barData = {
		labels: _.map(['日', '一', '二', '三', '四', '五', '六'], function(it){return '星期' + it;}),
		datasets: [{
			fillColor: 'rgba(220,220,220,0.5)',
			strokeColor: 'rgba(220,220,220,1)'
		}]
	};
	function showStatChart(){
		if(!lastQueryRecordList)
			return;
		
		var ll = [0, 0, 0, 0, 0, 0, 0];
		_.each(lastQueryRecordList, function(it){
			var dd = new Date(it.dd).getDay();
			ll[dd]++
		});

		if(chart == null){
			var ctx = document.getElementById('statChart').getContext('2d');
			chart = new Chart(ctx);
		}

		barData.datasets[0].data = ll;
		chart.Bar(barData);
	};

	// 显示统计记录
	var lastQueryDate = '';
	var lastQueryScaner;
	function showStatList(date, scaner){
		if(date)
			lastQueryDate = date;

		if(scaner){
			// 不作为查询条件
			if('-' == scaner){
				lastQueryScaner = null;
			}else{
				lastQueryScaner = scaner;
			}
		}

		// 显示查询的条件
		var banner = lastQueryDate;

		var scanerId = '';
		var meetingId = '';
		if(lastQueryScaner){
			banner += ' - ' + lastQueryScaner.name;
			scanerId = lastQueryScaner.id;
		}

		Req.get('/ibid/card/get-record-stat', 
			{companyId: User.get().companyId, date: lastQueryDate, scanerId: scanerId}, function(data){
			lastQueryDate = data.date;
			if(!banner)
				banner = lastQueryDate;

			showRecordInPager(data.ll, 1, banner);
		});
	}

	// 显示公司用户相关信息
	function showCompanyUser(user){
		if(user){
			$('#companyName').text('' + user.companyId + ' - ' + user.name);

			$('#labelChangePwd').show();
			$('#labelChangeUser a').text('切换用户');

			showScanerMeeting();
		}else{
			$('#companyName').text('');

			$('#labelChangePwd').hide();
			$('#labelChangeUser a').text('用户登录');

			clearQueryedList();
		}
	}

	function clearQueryedList(){
		var scanerMeetingRangeList = $('#scanerMeetingRangeList');
		var scanerList = $('#scanerList');
		var meetingList = $('#meetingList');

		scanerMeetingRangeList.empty();
		scanerList.empty();
		meetingList.empty();
	}

	// 显示打卡器、会议列表
	function showScanerMeeting(){
		var divider = '<li class="table-view-cell table-view-divider">{0}</li>';
		var tpl = '' + 
			'<li class="table-view-cell media">' + 
			'<a class="navigate-right" data-id="{0}" data-name="{1}">' + 
			'	  <div class="media-body">{1}</div>' + 
			'</a>' + 
			'</li>';

		var tplShowQr = '' + 
			'<li class="table-view-cell">' + 
			'<a class="navigate-right" href="/ibid/card/scaner?scanerId={0}" data-ignore="push">{1}</a>' + 
			'</li>'; 

		var scanerMeetingRangeList = $('#scanerMeetingRangeList');
		var scanerList = $('#scanerList');
		var meetingList = $('#meetingList');

		scanerMeetingRangeList.empty();
		scanerList.empty();
		meetingList.empty();

		Req.get('/ibid/card/get-scaner-meeting-list', 
			{companyId: User.get().companyId}, function(data){

			var str = '';
			var strScaner = '';
			var strMeeting = '';

			if(data.scanerList){
				str += divider.format('打卡器');

				_.each(data.scanerList, function(it){
					str += tpl.format(it.id, it.name);
					strScaner += tplShowQr.format(it.id, it.name);
				});
			}
			if(data.meetingList){
				str += divider.format('会议签到');

				var fm = 'MM-DD hh:mm';
				_.each(data.meetingList, function(it){
					var bt = it.beginTime ? moment(it.beginTime).format(fm) : '';
					var et = it.endTime ? moment(it.endTime).format(fm) : '';
					var meetingName = it.name + '<br />（{0}-{1}）'.format(bt, et);

					str += tpl.format(it.id, meetingName);
					strMeeting += tplShowQr.format(it.id, meetingName);
				});
			}

			scanerList.html(strScaner);
			meetingList.html(strMeeting);
			scanerMeetingRangeList.html(str);
		});	
	}
});